package com.hpxx.ylzswl.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.view.PagerAdapter;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.hpxx.ylzswl.R;
import com.hpxx.ylzswl.base.BaseActivity;
import com.hpxx.ylzswl.utils.FileUtil;
import com.hpxx.ylzswl.utils.ViewHolder;
import com.hpxx.ylzswl.views.PhotoViewPager;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import com.universal.frame.generalutils.SharedPreferencesUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import uk.co.senab.photoview.PhotoViewAttacher;

/**
 * Created by Administrator on 2017/8/11.
 */

public class LookImageActivity extends BaseActivity  {

    private PhotoViewPager viewPager;  //对应的viewPager
    private ArrayList<String> imgs;
    private int position;
    private List<View> viewList;
    private int Width;


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_look_image);
        setSwipeBackEnable(false);
    }

    @Override
    public void initView() {
        imgs = getIntent().getStringArrayListExtra("IMGS");
        position = getIntent().getIntExtra("POSITION", 0);
        viewPager = (PhotoViewPager) findViewById(R.id.viewpager);

        Width = SharedPreferencesUtil.getInt(this, "windowWidth");
        Log.i("tag", "Width = " + Width);
        initLookImage();
    }

    private void initLookImage() {
        viewList = new ArrayList<View>();// 将要分页显示的View装入数组中
        for (int i = 0; i < imgs.size(); i++) {
            View view = View.inflate(this, R.layout.item_look_img, null);
            ImageView iv_look_img = ViewHolder.get(view, R.id.iv_look_img);
            ImageView tv_down = ViewHolder.get(view, R.id.tv_down);
//            iv_look_img.setOnClickListener(new Linster(this, i));
            final int finalI = i;
            tv_down.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    download(imgs.get(finalI));
                }
            });
            Glide.with(this)
                    .load(imgs.get(i))
                    .placeholder(R.mipmap.rectangle_no_pic)
                    .error(R.mipmap.rectangle_no_pic)
                    .into(iv_look_img);
            //使图片实现可以放大缩小的功能
            PhotoViewAttacher mAttacher = new PhotoViewAttacher(iv_look_img);
            viewList.add(view);
        }
        viewPager.setAdapter(pagerAdapter);
        viewPager.setCurrentItem(position);
    }

    PagerAdapter pagerAdapter = new PagerAdapter() {

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            // TODO Auto-generated method stub
            return arg0 == arg1;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return viewList.size();
        }

        @Override
        public void destroyItem(ViewGroup container, int position,
                                Object object) {
            // TODO Auto-generated method stub
            container.removeView(viewList.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            // TODO Auto-generated method stub
            container.addView(viewList.get(position));
            return viewList.get(position);
        }
    };

//    @Override
//    public void linster(int position) {
//        finish();
//        overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
//    }

//    Transformation transformation = new Transformation() {
//
//        @Override
//        public Bitmap transform(Bitmap source) {
//
//            int targetWidth = Width;
//            if (source.getWidth() == 0) {
//                return source;
//            }
//
//            //如果图片大小大于等于设置的宽度，则按照设置的宽度比例来缩放
////            double aspectRatio = (double) source.getHeight() / (double) source.getWidth();
////            Log.i("tag","source.getHeight() = " + source.getHeight());
////            Log.i("tag","source.getWidth() = " + source.getWidth());
////            Log.i("tag","aspectRatio = " + aspectRatio);
//
//            //如果图片小于设置的宽度，则返回原图
//            if (source.getWidth() > targetWidth) {
//                return source;
//            } else {
//                //如果图片大小大于等于设置的宽度，则按照设置的宽度比例来缩放
//                double aspectRatio = (double) source.getHeight() / (double) source.getWidth();
//                Log.i("tag", "source.getHeight() = " + source.getHeight());
//                Log.i("tag", "source.getWidth() = " + source.getWidth());
//                Log.i("tag", "aspectRatio = " + aspectRatio);
//
//                int targetHeight = (int) (targetWidth * aspectRatio);
//                if (targetHeight != 0 && targetWidth != 0) {
//                    Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, false);
//                    if (result != source) {
//                        // Same bitmap is returned if sizes are the same
//                        source.recycle();
//                    }
//                    return result;
//                } else {
//                    return source;
//                }
//            }
//
//        }
//
//        @Override
//        public String key() {
//            return "transformation" + " desiredWidth";
//        }
//    };

    private void download(String url) {
//        //获得图片的地址
//        String url = mList.get(mPosition);

        //Target
        Target target = new Target() {

            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                String imageName = System.currentTimeMillis() + ".png";
                File dcimFile = FileUtil
                        .getDCIMFile(FileUtil.PATH_PHOTOGRAPH, imageName);

                FileOutputStream ostream = null;
                try {
                    ostream = new FileOutputStream(dcimFile);
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, ostream);
                    ostream.flush();
                    ostream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 其次把文件插入到系统图库
                try {
                    MediaStore.Images.Media.insertImage(getApplicationContext().getContentResolver(),
                            dcimFile.getAbsolutePath(), imageName, null);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                // 最后通知图库更新
                getApplicationContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" +  dcimFile.getAbsolutePath())));
//                Uri uri = Uri.fromFile(dcimFile);
//                String path = UriToPath.getRealFilePath(LookImageActivity.this, uri);
//                scanFileAsync(LookImageActivity.this, path);
//                scanDirAsync(LookImageActivity.this, dcimFile.getAbsolutePath());
                Toast.makeText(LookImageActivity.this, "图片保存成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {

            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {

            }
        };

        //Picasso下载
        Picasso.with(this).load(url).into(target);

    }

    //扫描指定文件
    public void scanFileAsync(Context ctx, String filePath) {
        Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        scanIntent.setData(Uri.fromFile(new File(filePath)));
        ctx.sendBroadcast(scanIntent);
    }

    //扫描指定目录
    public static final String ACTION_MEDIA_SCANNER_SCAN_DIR = "android.intent.action.MEDIA_SCANNER_SCAN_DIR";

    public void scanDirAsync(Context ctx, String dir) {
        Intent scanIntent = new Intent(ACTION_MEDIA_SCANNER_SCAN_DIR);
        scanIntent.setData(Uri.fromFile(new File(dir)));
        ctx.sendBroadcast(scanIntent);
    }
}
